package com.koudai.reader;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.ExistDialog;
import com.koudai.reader.util.Constant;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.vo.EndUser;

public class CateListActivity extends Activity implements OnScrollListener {

    public static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);
    GridView typelist;
    TypeListAdapter listAdapter;
    
    private Map<Integer, String> cateDataMapping = new HashMap<Integer, String>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.cate_list);
        
        typelist = (GridView) findViewById(R.id.grid);
        listAdapter = new TypeListAdapter();
        typelist.setAdapter(listAdapter);
        
        typelist.setOnScrollListener(this);

        ImageView searchBtn = (ImageView) findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View paramView) {

                Intent intent = new Intent();
                intent.setClass(CateListActivity.this, SearchBookActivity.class);
                CateListActivity.this.startActivity(intent);
            }
        });
    }

    public void onScroll(AbsListView view, int mFirstVisibleItem, int mVisibleItemCount, int mTotalItemCount) {


    }

    public void onScrollStateChanged(AbsListView view, int mScrollState) {

    }

    

    class AppListHttpRequest implements Runnable {

        @Override
        public void run() {

            try {
                
                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {
                        
                        showWait("loading");
                    }
                });
                
                HttpUtils.categoryList();

                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {
                        
                        
                        listAdapter.count = 0;
                        for (String cateName : Constant.allCategoryMapping.keySet()) {
                            
                            cateDataMapping.put(listAdapter.count++, cateName);
                        }

                        listAdapter.notifyDataSetChanged();
                        
                        waitClose();
                    }
                });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                sendMsg(100);
            }
        }
    }

    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        internalhandler.sendMessage(msg);
    }

    private Handler internalhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {

                case 100:
                    // app list 加载失败
                    waitClose();
                    Toast.makeText(getApplication(), "网络不给力", Toast.LENGTH_SHORT).show();
                    break;
                }
            }
            super.handleMessage(msg);
        }
    };
    private TextView score;
    private ImageView isVip;
    protected ProgressDialog processDialog;


    class TypeListAdapter extends BaseAdapter {
        LayoutInflater inflater;
        
        int count;
        public TypeListAdapter(){
            inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        @Override
        public int getCount() {
            
            return count;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.cate_list_item, null);
            final Button button = (Button)convertView.findViewById(R.id.image_item);
            button.setText(cateDataMapping.get(position));

            button.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    
                    Intent intent = new Intent();
                    intent.setClass(CateListActivity.this, CateBookListActivity.class);
                    intent.putExtra("cateName", cateDataMapping.get(position));
                    CateListActivity.this.startActivity(intent);
                    
                }

            });
            
            return convertView;
        }
        
    }
    
    protected void onResume() {
        super.onResume();
        score = (TextView) findViewById(R.id.score);
        score.setText(EndUser.getInstance().getGlodStr());
        
        isVip = (ImageView) findViewById(R.id.vip);
        if (EndUser.getInstance().isVip()) {
            isVip.setVisibility(View.VISIBLE);    
        } else {
            isVip.setVisibility(View.INVISIBLE);    
        }
        threadPool.schedule(new AppListHttpRequest(), 0, TimeUnit.MILLISECONDS);
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                ExistDialog.showDialog(this.getParent() == null ? this : this.getParent());
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }
    
    /**
     * 带等待图标的等待框 参数message：需要显示给用户的字符串
     * */
    public void showWait(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                processDialog = new ProgressDialog(CateListActivity.this);
                processDialog.setMessage(message);
                processDialog.setIndeterminate(true);
                processDialog.setCancelable(false);
                processDialog.show();

            }
        });

    }

    /**
     * 关闭等待框
     * */
    public void waitClose() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (processDialog != null && processDialog.isShowing()) {
                    processDialog.dismiss();
                }
            }
        });
    }
    
}
